"""
生成依赖项清单：pip freeze > requirements.txt
根据依赖项清单安装依赖项：pip install -r requirements.txt
查看依赖项清单：pip list
检查依赖项冲突：pip check

不使用多线程的场景
"""
from functools import wraps
import random
import time


# 装饰的参数是被装饰的函数或类，装饰器的返回值是带有装饰功能的函数
# 带参数的装饰器，需要对装饰器本身进行参数化
def record_time(write_log=print):

    def decorate(func):

        @wraps(func)
        def wrapper(*args, **kwargs):
            start = time.time()
            result = func(*args, **kwargs)
            end = time.time()
            write_log(func.__name__, end - start)
            return result

        return wrapper

    return decorate


def log_to_file(fname, duration):
    with open('func.log', 'a') as file:
        file.write(f'{fname}执行时间: {duration:.3f}秒\r\n')


# download = record_time(download)
@record_time(log_to_file)
def download(*, filename):
    print(f'开始下载{filename}.')
    time.sleep(random.randint(3, 6))
    print(f'{filename}下载完成.')


@record_time(log_to_file)
def upload(*, filename):
    print(f'开始上传{filename}.')
    time.sleep(random.randint(4, 8))
    print(f'{filename}上传完成.')


@record_time()
def main():
    print(download.__name__)
    print(upload.__name__)
    download(filename='Python从入门到住院.pdf')
    download(filename='MySQL从删库到跑路.avi')
    upload(filename='Linux从精通到放弃.mp3')
    # 取消装饰器的作用
    # download.__wrapped__(filename='MySQL从删库到跑路.avi')
    # upload.__wrapped__(filename='Linux从精通到放弃.mp3')


if __name__ == '__main__':
    main()
